//
// Created by LoveHoneyYou on 2024-11-17.
//

#include "WorkerThread.h"
WorkerThread::WorkerThread(int index)
{
    event_loop_ = nullptr;
    thread_id_ = std::thread::id();
    name_ = "SubThread-" + std::to_string(index);
}

WorkerThread::~WorkerThread()
{
    if(thread_->joinable())
    {
        thread_->join();
    }
    delete thread_;
    thread_ = nullptr;
}

void WorkerThread::Run()
{
    thread_ = new std::thread(&WorkerThread::Running,this);
    std::unique_lock<std::mutex> locker(mutex_);
    while(event_loop_ == nullptr)
    {
        cond_.wait(locker);
    }
}

void WorkerThread::Running()
{
    mutex_.lock();
    event_loop_ = new EventLoop(name_);
    mutex_.unlock();
    cond_.notify_one();
    event_loop_->Run();
}
